//
//  BindCardMainView.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2020/3/9.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit

@objc protocol BindCardMainViewDelegate: NSObjectProtocol {
    func didSendCodeMsg()
    func didEndEdit(textField: UITextField)
    func didSureAddCard(msgCode: String)
    @objc optional func didCancelAction()
}

class BindCardMainView: UIView {
    weak var delegate: BindCardMainViewDelegate?
    
    private var viewModel = BindCardViewModel(model: BindCardModel())
    
    private lazy var sendCodeView = UINib.loadViewFrom(BindCardSendCodeView.self)
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        self.alpha = 0.0
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        self.frame = mainWindow.bounds
        
        sendCodeView.layer.cornerRadius = 16
        sendCodeView.layer.masksToBounds = true
        sendCodeView.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
            make.size.equalTo(CGSize(width: screenW - 50, height: 290))
        }
    }
    
    private func dismiss() {
        switch viewModel.status {
        case .canBind, .noCard: dimissSendCode()
        default:
            break
        }
    }
    
    func show(in view: UIView? = nil, vm: BindCardViewModel) {
        let tempView = view == nil ? mainWindow : view
        tempView?.addSubview(self)
        
        viewModel = vm
        
        switch vm.status {
        case .canBind, .noCard:
            showSendCode()
        default:
            break
        }
    }
    
    private func showSendCode() {
        sendCodeView.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
        sendCodeView.configure(with: viewModel)
        sendCodeView.delegate = self
        addSubview(sendCodeView)
        
        UIView.animate(withDuration: 0.25, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0, options: .curveLinear, animations: {
            self.alpha = 1.0
            self.sendCodeView.transform = CGAffineTransform(scaleX: 1, y: 1)
        })
    }
    
    // MARK: - dimiss
    private func dimissSendCode() {
        UIView.animate(withDuration: 0.25, delay: 0, options: .curveLinear, animations: {
            self.sendCodeView.transform = CGAffineTransform(scaleX: 0.0001, y: 0.0001)
        }) { _ in
            self.alpha = 0.0
            self.removeFromSuperview()
        }
    }
}

extension BindCardMainView: BindCardMainViewDelegate {
    func didCancelAction() {
        dismiss()
    }
    
    func didEndEdit(textField: UITextField) {
        delegate?.didEndEdit(textField: textField)
    }
    
    func didSureAddCard(msgCode: String) {
        dismiss()
        delegate?.didSureAddCard(msgCode: msgCode)
    }
    
    func didSendCodeMsg() {
        delegate?.didSendCodeMsg()
    }
}
